/*
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改日期     修改人员  修改说明
 * ========    =======  ============================================
 * 2021/4/1  lisy31662  新增
 * ========    =======  ============================================
 */
package com.sansi.pencilbook.util;

import cn.hutool.core.util.ArrayUtil;
import org.apache.commons.lang.ArrayUtils;

import java.util.Arrays;

/**
 * 功能说明: 数组工具类
 *
 * @author lisy31662
 */
public class ArraysUtil {

  public static double[] addAll(double[] array1, double[] array2) {
    return ArrayUtils.addAll(array1, array2);
  }

  public static double[][] addAll(double[][] array1, double[][] array2) {
    double[][] allArray = new double[array1.length+1][array2[0].length];
    System.arraycopy(array1, 0, allArray, 0, array1.length);
    System.arraycopy(array2, 0, allArray, array1.length, array2.length);
    return allArray;
  }

  /**
   * 获得数组从大至小的前K个下标
   * @param K
   * @param array
   * @return
   */
  public static int[] getMaxArrayIndex(int K, double[] array) {
    if (K>array.length) {
      K=array.length;
    }
    double[] maxArray = new double[K+1];
    int[] index = new int[K+1];
    Arrays.fill(index, Integer.MIN_VALUE);
    Arrays.fill(maxArray, Double.MIN_VALUE);
    for (int i=0;i<array.length;i++) {
      maxArray[K] = array[i];
      index[K] = i;
      for (int j=K-1;j>=0;j--) {
        if (Double.isNaN(array[i])) {
          continue;
        }
        if (maxArray[j]<maxArray[j+1]) {
          maxArray[j] = maxArray[j] + maxArray[j+1];
          index[j] = index[j] + index[j+1];
          maxArray[j+1] = maxArray[j] - maxArray[j+1];
          index[j+1] = index[j] - index[j+1];
          maxArray[j] = maxArray[j] - maxArray[j+1];
          index[j] = index[j] - index[j+1];
        }
      }
    }
    index=Arrays.copyOf(index, K);
    while (ArrayUtils.indexOf(index, Integer.MIN_VALUE)>-1) {
      index = ArrayUtils.removeElement(index, Integer.MIN_VALUE);
    }
    return index;
  }

  /**
   * 获得排序后(从大到小)原数组对应下标
   * @param array
   * @return
   */
  public static int[] getSortIndex(double[] array) {
    int[] Index= new int[array.length];
    for(int i=0;i<array.length;i++){
      Index[i]=i;
    }
    for(int i=0;i<array.length;i++){
      for(int j=0;j<array.length-i-1;j++){
        if(array[j]<array[j+1]){
          array[j] = array[j] + array[j+1];
          array[j+1] = array[j] - array[j+1];
          array[j] = array[j] - array[j+1];

          Index[j] = Index[j] + Index[j+1];
          Index[j+1] = Index[j] - Index[j+1];
          Index[j] = Index[j] - Index[j+1];
        }
      }
    }
    return Index;
  }

  public static Double[] wrap(double[] array) {
    return ArrayUtil.wrap(array);
  }

  public static double[] unwrap(Double[] array) {
    return ArrayUtil.unWrap(array);
  }

}
